package com.zhangfei.controller;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
public class RedisLockController {

    @Resource
    private RedissonClient redissonClient;


    private static final String LOCK_KEY = "myLock";

    @GetMapping("/redissonLockTest")
    @ResponseBody
    public Boolean redissonLockTest() throws InterruptedException {

        // 获取锁对象
        RLock lock = redissonClient.getLock(LOCK_KEY);

        // 模拟多个线程尝试获取锁
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                try {
                    // 尝试获取锁，最多等待10秒，获取锁后10秒自动释放
                    lock.lock(10, TimeUnit.SECONDS);
                    System.out.println(Thread.currentThread().getName() + " 获取到锁，开始处理任务...");
                    Thread.sleep(2000); // 模拟处理任务需要花费一些时间
                    System.out.println(Thread.currentThread().getName() + " 处理任务完成，释放锁...");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    // 无论如何，最后都要确保锁被释放
                    lock.unlock();
                }
            }).start();
        }

        // 让主线程等待一段时间，以便观察其他线程的行为
        Thread.sleep(10000);


        return true;
    }


}
